package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 菜品信息分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器,添加过滤条件和排序
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Dish::getName, name).orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo, queryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = new ArrayList<>();
        for (Dish dish : records) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            //分类id
            Long categoryId = dish.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            dishDto.setCategoryName(category.getName());
            list.add(dishDto);
        }
        dishDtoPage.setRecords(list);

        //执行分页查询
        return R.success(dishDtoPage);
    }


    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);

        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId();
        redisTemplate.delete(key);

////        //清理所有菜品的缓存数据
////        //获取所有以dish_xxx开头的key
//        Set keys = redisTemplate.keys("dish_*");
////         //删除这些key
//        redisTemplate.delete(keys);
        return R.success("添加菜品成功！");
    }


    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);

        //清理某个分类下面的菜品缓存数据
//        String key = "dish_" + dishDto.getCategoryId();
//        redisTemplate.delete(key);

        //清理所有菜品的缓存数据
//        //获取所有以dish_xxx开头的key
        Set keys = redisTemplate.keys("dish_*");
//         //删除这些key
        redisTemplate.delete(keys);
        return R.success("修改成功！");
    }


    /**
     * 停售商品
     *
     * @param status,ids
     * @return
     */

    @PostMapping("/status/{status}")
    public R<String> stop(@PathVariable int status,@RequestParam List<Long> ids) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids != null, Dish::getId, ids);

        List<Dish> list = dishService.list(queryWrapper);

        for (Dish dish : list) {
            dish.setStatus(status);
            dishService.updateById(dish);

        }

        return R.success("修改成功！");
    }


    /**
     * 根据菜品分类条件查询对应的菜品数据
     * @param
     * @return
     */

//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId())
//                .orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(queryWrapper);
//        return R.success(list);
//    }


    @GetMapping("/list")

    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtoList=null;
        //动态构造key
        String key = "dish_" + dish.getCategoryId();
        //先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList!=null){
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //根据条件，按照菜品分类查询菜品且状态为1（起售状态）的菜品
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId())
                        .eq(Dish::getStatus,1)
                                .orderByAsc(Dish::getSort)
                                        .orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        // List<Dish>   ---> List<DishDto>
        dishDtoList=new ArrayList<>();
        //遍历 List<Dish> 集合，获取每一个Dish对象，转变成DishDto对象，放入到新的集合 List<DishDto>
        //将查询出来的Dish数据给DishDto赋值
        for (Dish dish1 : list) {
            DishDto dishDto = new DishDto();
            //1.把dish的属性值copy给dishDto
            BeanUtils.copyProperties(dish1,dishDto);

            //根据菜品id查询出该菜品所属套餐或菜系
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            //把dish所属菜系名称给DishDto
            if (category!=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //2.查询菜品的口味数据
            Long dishId = dish1.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            //3.将菜品的口味列表 set给 dishDto
            dishDto.setFlavors(dishFlavors);

            //4.将dishDto放入到 dishDtos 集合中
            dishDtoList.add(dishDto);

        }

        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

    /**
     * 删除菜品
     *
     * @param
     * @return
     */
    @DeleteMapping()
    public R<String> delete(@RequestParam List<Long> ids) {
        dishService.deleteWithFlavor(ids);


        return R.success("删除成功！");
    }
}

